package com.galaxy.commom.base.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;

/**
 * 防XSS漏洞过滤器
 *
 * @author caijinbang
 * @date 2018/9/8 22:51
 */

@Slf4j
@Order(1)
@WebFilter(filterName = "xssFilter", urlPatterns = "/*")
public class XssFilter implements Filter {

  /**
   * 不包括的路径
   */
  private String[] excludePaths = null;

  /**
   * 初始化
   * @param filterConfig 过滤配置
   * @throws ServletException servlet异常
   */
  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
    log.debug("init XssFilter");
    String excludePath = filterConfig.getInitParameter("excludePaths");
    if (StringUtils.isNotBlank(excludePath)) {
      excludePaths = excludePath.split(",");
    }
  }

  /**
   * 过滤
   *
   * @param servletRequest 请求
   * @param servletResponse 响应
   * @param filterChain 过滤链
   * @throws IOException io异常
   * @throws ServletException servlet异常
   */
  @Override
  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
      FilterChain filterChain) throws IOException, ServletException {
    log.debug("XssFilter.doFilter. request uri: {}",
        ((HttpServletRequest) servletRequest).getRequestURI());
    if (excludePaths != null) {
      HttpServletRequest request = (HttpServletRequest) servletRequest;
      String uri = request.getRequestURI();
      // 排除部分URL不做过滤。
      for (String str : excludePaths) {
        if (uri.indexOf(str) >= 0) {
          log.debug("该URL不作校验：" + uri);
          filterChain.doFilter(servletRequest, servletResponse);
          return;
        }
      }
    }
    XssHttpRequestWrapper xssHttpServletRequest = new XssHttpRequestWrapper(
        (HttpServletRequest) servletRequest);
    filterChain.doFilter(xssHttpServletRequest, servletResponse);
  }

  @Override
  public void destroy() {

  }
}
